package com.hmall.search;

import com.alibaba.fastjson.JSON;
import com.google.common.collect.Lists;
import com.hmall.common.clients.ItemClients;
import com.hmall.common.dto.PageDTO;
import com.hmall.common.dto.RequestParams;


import com.hmall.common.pojo.Item;
import com.hmall.common.pojo.ItemDoc;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;

import java.io.IOException;
import java.util.List;

@SpringBootTest
public class InsertSearch {

    @Autowired
    ItemClients itemClients;

    @Autowired
    RestHighLevelClient client;


    @Test
    public void insertItem() {
//        RequestParams requestParams = new RequestParams();
//        requestParams.setPage(1);
//        requestParams.setSize(90000);
//        PageDTO<Item> all = itemClients.findAll(requestParams);
//        BulkRequest request = new BulkRequest();
//        List<Item> list = all.getList();
//        //工具类拆分数据集合
//        List<List<Item>> lists = Lists.partition(list, 300);
//        for (List<Item> items : lists) {
//            try {
//                for (Item item : items) {
//                    ItemDoc itemDoc = new ItemDoc(item);
//                    request.add(new IndexRequest("item").id(itemDoc.getId().toString()).source(JSON.toJSONString(itemDoc), XContentType.JSON));
//                }
//                client.bulk(request, RequestOptions.DEFAULT);
//            } catch (IOException e) {
//                e.printStackTrace();
//            }
//        }
        RequestParams params = new RequestParams();
        int i=1;
        while (true) {
            params.setPage(i);
            params.setSize(1000);
            List<Item> list = itemClients.findAll(params).getList();
            if(list.size()==0){
                break;
            }
            BulkRequest request = new BulkRequest();
            for (Item item : list) {
                ItemDoc itemDoc = new ItemDoc(item);
                request.add(new IndexRequest("item")
                        .id(itemDoc.getId().toString())
                        .source(JSON.toJSONString(itemDoc), XContentType.JSON));
            }
            try {
                client.bulk(request, RequestOptions.DEFAULT);
            } catch (IOException e) {
                e.printStackTrace();
            }
            i++;
        }


    }
}
